import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from '@/utils/request'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('admin_info') || '{}'))
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value.username || '')
  const userRole = computed(() => userInfo.value.role || '')

  // 登录
  const login = async (credentials) => {
    isLoading.value = true
    try {
      const response = await axios.post('/api/auth/admin/login', credentials)
      
      if (response.success) {
        const { token: newToken, admin } = response.data
        
        // 保存到状态
        token.value = newToken
        userInfo.value = admin
        
        // 保存到本地存储
        localStorage.setItem('admin_token', newToken)
        localStorage.setItem('admin_info', JSON.stringify(admin))
        
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请检查网络连接' 
      }
    } finally {
      isLoading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_info')
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem('admin_info', JSON.stringify(userInfo.value))
  }

  // 检查登录状态
  const checkAuth = () => {
    const savedToken = localStorage.getItem('admin_token')
    const savedUserInfo = localStorage.getItem('admin_info')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      userInfo.value = JSON.parse(savedUserInfo)
      return true
    }
    
    return false
  }

  return {
    // 状态
    token,
    userInfo,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    username,
    userRole,
    
    // 方法
    login,
    logout,
    updateUserInfo,
    checkAuth
  }
})